package com.echo.servlet;


import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.PhraseQuery;
import org.apache.lucene.search.Searcher;

public class QueryServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(QueryServlet.class.getName());
	private static String FIELD_NAME = "content";
	private static String INDEX_DIR = "D:\\luceneIndex";

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		Long startTime = new Date().getTime();
		StringBuffer candidateRest = new StringBuffer();
		Sorter sorter = new Sorter();
//		try{
//			RankMachine rankMachine = new RankMachine();
//		}catch (Exception e){
//			e.printStackTrace();
//		}
		
		int[] restList = new int[10];
		int restNum = 0;
		//fuzzy query
//		Query query = new WildcardQuery(new Term("reviewContent", "the"));
		//multi-semantic query 
//		Query query1 = MultiFieldQueryParser.parse(new String[]{"popular", "xxxx"}, new String[]{"reviewContent", "restId"}, analyzer);
		
		//watch out for the uppercase
		String queryTerm = req.getParameter("queryTerm");
		String[] querys = queryTerm.split(" ");
		PhraseQuery query = new PhraseQuery();
		for(int m=0; m<querys.length; m++){
			query.add(new Term("reviewContent", querys[m]));
		}
		query.setSlop(0);
		HashMap<String, Integer> restMap = new HashMap<String, Integer>();
		HashMap<String, String> snippetMap = new HashMap<String, String>();
		StringBuffer snippetList = new StringBuffer();
		
		try{
			Searcher searcher = new IndexSearcher(INDEX_DIR);
			Hits hits = searcher.search(query);
			for(int i=0; i<hits.length(); i++){
//				System.out.println(hits.doc(i).get("restId")+" -- "+hits.doc(i).get("reviewId")+" -- "+hits.doc(i).get("reviewType"));
//				System.out.println(hits.score(i));
				String tempRest = hits.doc(i).get("restId");
				if (restMap.get(tempRest)==null){
					restMap.put(tempRest, 1);
				}else{
					int temp = restMap.get(tempRest);
					restMap.put(tempRest, temp+1);
				}
				if(snippetMap.get(tempRest)==null){
					String reviewId = hits.doc(i).get("reviewId");
					String snippet = "<font color='red'>"+reviewId+"</font>";
					snippetMap.put(tempRest, snippet);
				}
			}
			
			Iterator iter = restMap.keySet().iterator();
			System.out.println(restMap.size());
			int[] frequentRest = new int[restMap.size()+1];
			int i=0;
			Object key = null;
			while(iter.hasNext()){
				key = iter.next();
				frequentRest[i] = (Integer)restMap.get(key);
//				System.out.println((String)key+": "+ myTreeMap.get(key));
				i++;
			}
			sorter.quickSort(frequentRest, 0, restMap.size());
			//output the top20 restaurant which has the most frequent terms of the query
			for(int j=frequentRest.length-1; j>frequentRest.length-6; j--){
				if((frequentRest[j]>0)&&(frequentRest[j]!=frequentRest[j-1])){
		 			System.out.print(frequentRest[j]+" ");
					Iterator tempIter = restMap.keySet().iterator();
					Object tempKey = null;
					while(tempIter.hasNext()){
						tempKey = tempIter.next();
						if(frequentRest[j]==(Integer)restMap.get(tempKey)){
							System.out.print((String)tempKey+" ");
							candidateRest.append((String)tempKey+" ");
//							int score = rankMachine.getScore((String)tempKey);
//							System.out.println(score);
							String tempSnippet = snippetMap.get((String)tempKey);
							snippetList.append(tempSnippet+"--");
						}
					}
				}else{
					continue;
				}
			}
			
			EmergingPattern ep = new EmergingPattern();
			try{
				String emergingResult = ep.getEmergingPattern(candidateRest.toString());
				ArrayList<String> termList = ep.termList;
				String[] candidateRestTemp = candidateRest.toString().split(" ");
				Miner miner = new Miner(candidateRestTemp.length, ep.termNum);
				miner.computeNormTF(emergingResult);
				miner.computeTFR();
				Long endTime = new Date().getTime();
//				System.out.println(emergingResult);
				System.out.println("runtime is: "+ (endTime-startTime));
				ArrayList<Float> temp = new ArrayList<Float>();
				temp = miner.TFRList;
				for(int n=0; n<candidateRestTemp.length; n++){
					ArrayList<Float> tempResult = new ArrayList<Float>();
					for(int x=0; x<termList.size(); x++){
						tempResult.add(x, temp.get(n*termList.size()+x));
					}
					ChartTest ct = new ChartTest();
					ct.drawSingleChart(tempResult, termList, (float)0.4, candidateRestTemp[n]);
				}
				HttpSession session = req.getSession();
				session.setAttribute("restList", candidateRest.toString());
				session.setAttribute("snippetList", snippetList.toString());
				resp.sendRedirect("SearchResult.jsp");
			}catch(Exception e){
				e.printStackTrace();
			}
		}catch(IOException e){
			e.printStackTrace();
		}
	}
	
	
}
